package com.taotao.service.impl;

import java.io.IOException;

import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.PictureResult;
import com.taotao.service.PictureService;
import com.taotao.utils.FastDFSClient;

@Service
public class PictureServiceImpl implements PictureService {

	@Value("${IMAGE_SERVER_URL}")
	private String imageServerURL;
	@Override
	public PictureResult uploadPictureFromMultipartFile(MultipartFile picFile) {
		PictureResult result = new PictureResult();
		if (picFile.isEmpty()) {
			result.setError(1);
			result.setMessage("图片为空");
			return result;
		}
		// 上传图片到服务器
		try {
			String originalFilename = picFile.getOriginalFilename();
			String originalFilenameType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			FastDFSClient fastDFSClient = FastDFSClient.getFastDFSClient();
			String url = imageServerURL + fastDFSClient.uploadFile(picFile.getBytes(), originalFilenameType);
			// 成功标志与图片的url
			result.setError(0);
			result.setUrl(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public PictureResult uploadPictureFromBase64(String base64Data) {
		PictureResult result = new PictureResult();
		if (base64Data == null || base64Data.isEmpty()) {
			result.setError(1);
			result.setMessage("图片为空");
			return result;
		}
		String dataPrix = "";
		String data = "";
		String[] d = base64Data.split("base64,");
		if (d != null && d.length == 2) {
			dataPrix = d[0];
			data = d[1];
		} else {
			result.setError(2);
			result.setMessage("上传失败，数据不合法");
			return result;
		}
		String suffix = "";
		if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
			// 编码的jpeg图片数据
			suffix = "jpg";
		} else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
			// 编码的icon图片数据
			suffix = ".ico";
		} else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
			// 编码的gif图片数据
			suffix = "gif";
		} else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
			// 编码的png图片数据
			suffix = "png";
		} else {
			result.setError(3);
			result.setMessage("上传图片格式不合法");
			return result;
		}
		byte[] bs = Base64Utils.decodeFromString(data);
		// 上传到fdfs
		try {
			FastDFSClient fastDFSClient = FastDFSClient.getFastDFSClient();
			String url = imageServerURL + fastDFSClient.uploadFile(bs, suffix);
			// 成功标志与图片的url
			result.setError(0);
			result.setUrl(url);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MyException e) {
			e.printStackTrace();
		}
		return result;
	}

}
